package com.ttmusic.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;

import com.ttmusic.core.MusicManager.LoopMode;
import com.ttmusic.entity.AbstractMusic;
import com.ttmusic.entity.User;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;


/**
 * 
 * @author wuchangyong
 *
 */
public class SharedPreferencesUtil {

    public static final String ENV = "env";
    public static final String ENV_OBJ = "ENV_OBJ";

    /**
     * 获取是否过滤文件大小
     *
     * @param context
     * @return
     */
    public static boolean isFilterSize(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(ENV, Context.MODE_PRIVATE);
        return preferences.getBoolean(IContain.ENV_IS_FILTER_SIZE, true);
    }

    /**
     * 设置是否过滤文件大小
     *
     * @param context
     * @param flag
     */
    public static void setIsFilterSize(Context context, boolean flag) {
        SharedPreferences preferences = context.getSharedPreferences(ENV, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(IContain.ENV_IS_FILTER_SIZE, flag);
        editor.commit();
    }

    /**
     * 获取是否过滤文件时长
     *
     * @param context
     * @return
     */
    public static boolean isFilterDuration(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(ENV, Context.MODE_PRIVATE);
        return preferences.getBoolean(IContain.ENV_IS_FILTER_DURATION, true);
    }

    /**
     * 设置是否过滤文件时长
     *
     * @param context
     * @param flag
     */
    public static void setIsFilterDuration(Context context, boolean flag) {
        SharedPreferences preferences = context.getSharedPreferences(ENV, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(IContain.ENV_IS_FILTER_DURATION, flag);
        editor.commit();
    }

    /**
     * 获取已经启动过的次数
     *
     * @param context
     * @return
     */
    public static int getHasRunCount(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(ENV, Context.MODE_PRIVATE);
        return preferences.getInt(IContain.ENV_HAS_RUN_COUNT, 0);
    }

    /**
     * 设置APP运行次数 每次运行APP 此次数加1
     * @param context
     * @param hasRunCount
     */
    public static void setHasRunCount(Context context, int  hasRunCount) {
        SharedPreferences preferences = context.getSharedPreferences(ENV, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt(IContain.ENV_HAS_RUN_COUNT, hasRunCount);
        editor.commit();
    }
    
    /**
     * 获取是否自动登录
     * @param context
     * @return
     */
    public static boolean isAutoLogin(Context context) {
    	SharedPreferences preferences = context.getSharedPreferences(ENV, Context.MODE_PRIVATE);
        return preferences.getBoolean(IContain.IS_AUTO_LOGIN, false);
    }
    /**
     * 设置是否自动登录
     * @param context
     * @param isAutoLogin
     */
    public static void setIsAutoLogin(Context context, boolean isAutoLogin) {
    	SharedPreferences preferences = context.getSharedPreferences(ENV, Context.MODE_PRIVATE);
    	SharedPreferences.Editor editor = preferences.edit();
    	editor.putBoolean(IContain.IS_AUTO_LOGIN, isAutoLogin);
        editor.commit();
    }
    
    /**
     * 获取原先保存的登录用户
     * @param context
     * @return
     */
    public static User getCurrentLoginUser(Context context) {
    	return getObject(context, IContain.CURRENT_LOGIN_USER, User.class);
    }
    /**
     * 登录成功后设置当前用户
     * @param context
     * @param user
     */
    public static void setCurrentLoginUser(Context context, User user) {
    	saveObject(context, IContain.CURRENT_LOGIN_USER, user);
    }
    
    /**
     * 退出APP后再次进入APP时读取之前保存的循环模式
     * @param context
     * @return
     */
    public static LoopMode getCurrentLoopMode(Context context) {
    	return getObject(context, IContain.CURRENT_LOOP_MODE, LoopMode.class);
    }
    /**
     * 退出APP时保存当前的循环模式
     * @param context
     * @return
     */
    public static void setCurrentLoopMode(Context context, LoopMode loopMode) {
    	saveObject(context, IContain.CURRENT_LOOP_MODE, loopMode);
    }
    
//    /**
//     * 退出APP后再次运行APP时获取当前展示的主界面的第几个tab标签
//     * @param context
//     * @return
//     */
//    public static int getMainTabIndex(Context context) {
//    	SharedPreferences preferences = context.getSharedPreferences(ENV, Context.MODE_PRIVATE);
//    	return preferences.getInt(IContain.MAIN_TAB_INDEX, 0);
//    }
//    /**
//     * 退出APP时设置当前展示的主界面的第几个tab标签
//     * @param context
//     * @param mainTabIndex
//     */
//    public static void setMainTabIndex(Context context, int mainTabIndex) {
//    	SharedPreferences preferences = context.getSharedPreferences(ENV, Context.MODE_PRIVATE);
//    	SharedPreferences.Editor editor = preferences.edit();
//    	editor.putInt(IContain.MAIN_TAB_INDEX, mainTabIndex);
//        editor.commit();
//    }
//    /**
//     * 退出APP后再次运行APP时获取前一次退出时保存的播放歌曲编号
//     * @param context
//     * @return
//     */
//    public static int getCurrentPlayingIndex(Context context) {
//    	SharedPreferences preferences = context.getSharedPreferences(ENV, Context.MODE_PRIVATE);
//    	return preferences.getInt(IContain.CURRENT_PLAYING_INDEX, -1);
//    }
//    /**
//     * 退出APP时设置当前正在播放的歌曲编号
//     * @param context
//     * @param currentPlayingIndex
//     */
//    public static void setCurrentPlayingIndex(Context context, int currentPlayingIndex) {
//    	SharedPreferences preferences = context.getSharedPreferences(ENV, Context.MODE_PRIVATE);
//    	SharedPreferences.Editor editor = preferences.edit();
//    	editor.putInt(IContain.CURRENT_PLAYING_INDEX, currentPlayingIndex);
//        editor.commit();
//    }
//    /**
//     * 退出APP后再次运行APP时获取前一次退出时保存的播放歌曲进度
//     * @param context
//     * @return
//     */
//    public static int getCurrentPlayingProgress(Context context) {
//    	SharedPreferences preferences = context.getSharedPreferences(ENV, Context.MODE_PRIVATE);
//    	return preferences.getInt(IContain.CURRENT_PLAYING_PROGRESS, 0);
//    }
//    /**
//     * 退出APP时设置当前正在播放的歌曲进度
//     * @param context
//     * @param currentPlayingIndex
//     */
//    public static void setCurrentPlayingProgress(Context context, int currentPlayingProgress) {
//    	SharedPreferences preferences = context.getSharedPreferences(ENV, Context.MODE_PRIVATE);
//    	SharedPreferences.Editor editor = preferences.edit();
//    	editor.putInt(IContain.CURRENT_PLAYING_PROGRESS, currentPlayingProgress);
//        editor.commit();
//    }

    /**
     * 获取最近播放的音乐 
     * @param context
     * @return
     */
    public static AbstractMusic getRecentMusic(Context context){
        return getObject(context, IContain.ENV_RECENT_MUSIC, AbstractMusic.class);
    }

    /**
     * 保存最近播放的音乐  提供给退出APP再次运行APP时可以直接获取出来
     * @param context
     * @param music
     */
    public static void saveRecentMusic(Context context, AbstractMusic music){
        saveObject(context, IContain.ENV_RECENT_MUSIC, music);
    }
    

    /**
     * 针对复杂类型存储<对象>
     * @param key
     * @param object
     */
    public static void saveObject(Context context, String key, Object object) {
        SharedPreferences sp = context.getSharedPreferences(ENV_OBJ, Context.MODE_PRIVATE);

        //创建字节输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //创建字节对象输出流
        ObjectOutputStream out = null;
        try {
            //然后通过将字对象进行64转码，写入key值为key的sp中
            out = new ObjectOutputStream(baos);
            out.writeObject(object);
            String objectVal = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
            SharedPreferences.Editor editor = sp.edit();
            editor.putString(key, objectVal);
            editor.commit();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 从SharedPreferences中获取一个对象出来
     * @param context
     * @param key
     * @param clazz
     * @return
     */
    public static <T> T getObject(Context context, String key, Class<T> clazz) {
        SharedPreferences sp = context.getSharedPreferences(ENV_OBJ, Context.MODE_PRIVATE);
        if (sp.contains(key)) {
            String objectVal = sp.getString(key, null);
            byte[] buffer = Base64.decode(objectVal, Base64.DEFAULT);
            //一样通过读取字节流，创建字节流输入流，写入对象并作强制转换
            ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
            ObjectInputStream ois = null;
            try {
                ois = new ObjectInputStream(bais);
                @SuppressWarnings("unchecked")
				T t = (T) ois.readObject();
                return t;
            } catch (StreamCorruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (bais != null) {
                        bais.close();
                    }
                    if (ois != null) {
                        ois.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
